package com.fagejiang.nebula;

import java.sql.*;
import java.util.List;

/**
 * TODO
 *
 * @author 发哥讲Java
 * @version 1.0
 * @date 2021-03-30 10:07
 */
public class DbUtil {
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("org.postgresql.Driver");
            String url = "jdbc:postgresql://192.168.0.44:5433/nightHawk_shaoxing";
            String username = "postgres";
            String password = "baianpg2020";
            conn = DriverManager.getConnection(url, username, password);
            return conn;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Connection getMysqlConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://192.168.0.44:13306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
            String username = "root";
            String password = "baian2020mql";
            conn = DriverManager.getConnection(url, username, password);
            return conn;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void saveData(List<Object[]> paramsList) throws SQLException {
        final Connection conn = getMysqlConnection();
        final PreparedStatement pstat = conn.prepareStatement("insert  into ba_statistics_center(id,num,title,parent_num,total)values(?,?,?,?,?)");
        conn.setAutoCommit(false);
        if (paramsList != null && paramsList.size() > 0) {
            for (Object[] params : paramsList) {
                for (int i = 0; i < params.length; i++) {
                    pstat.setObject(i + 1, params[i]);
                }
                pstat.addBatch();
            }
        }
        final int[] ints = pstat.executeBatch();
        conn.commit();
        System.out.println(ints.length);
        close(null, pstat, conn);
    }

    public static void close(ResultSet rs, Statement stmt, Connection connection) {

        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
